<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="navbar-content">
        <view class="nav-left" @click="onBack">
          <image
            src="https://img.alicdn.com/imgextra/i4/O1CN01kUiDtJ1YtNhsWuQhs_!!6000000003115-2-tps-200-200.png"
            mode="aspectFit"
            class="back-icon"
          />
        </view>
        <view class="nav-center">
          <text class="nav-title">{{ '文件夹名称:' + folder?.folderName || '回忆集' }}</text>
          <!-- <text class="nav-subtitle">{{ sortedMemories.length }}条回忆</text> -->
        </view>
        <!-- <view class="nav-right">
          <view class="action-btn" @click="showSort">
            <image
              src="https://img.alicdn.com/imgextra/i2/O1CN01Rpgxpk1vufCbYYrkA_!!6000000006225-2-tps-200-200.png"
              mode="aspectFit"
              class="action-icon"
            />
          </view>
          <view class="action-btn primary" @click="createMemory">
            <image
              src="https://img.alicdn.com/imgextra/i2/O1CN01GOtOHk1x9KsiM6Z5v_!!6000000006397-2-tps-200-200.png"
              mode="aspectFit"
              class="action-icon"
            />
            <text>新建</text>
          </view>
        </view> -->
      </view>

      <!-- 搜索栏 -->
      <view class="search-wrapper">
        <view class="search-bar">
          <image
            src="https://img.alicdn.com/imgextra/i1/O1CN01K4L7WY1YwXNX5hOYV_!!6000000003124-2-tps-200-200.png"
            mode="aspectFit"
            class="search-icon"
          />
          <input
            type="text"
            placeholder="搜索回忆内容..."
            v-model="searchText"
            placeholder-class="search-placeholder"
          />
        </view>
      </view>
    </view>

    <!-- 回忆列表 -->
    <scroll-view
      class="memories-scroll"
      scroll-y
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 列表头部统计 -->
      <view class="list-header">
        <view class="header-main">
          <text class="total-count">{{ sortedMemories.length }}</text>
          <text class="total-label">条回忆</text>
        </view>
        <text class="update-time">最近更新 {{ getLastUpdateTime() }}</text>
      </view>

      <view class="memories-list">
        <template v-if="isLoading">
          <view class="loading-skeleton" v-for="i in 3" :key="i">
            <view class="skeleton-content">
              <view class="skeleton-title" />
              <view class="skeleton-text" v-for="j in 2" :key="j" />
            </view>
          </view>
        </template>

        <template v-else-if="sortedMemories.length">
          <view
            class="memory-card"
            v-for="memory in sortedMemories"
            :key="memory.id"
            @click="openMemory(memory.id)"
          >
            <view class="memory-content">
              <view class="memory-main">
                <view class="memory-header">
                  <text class="title">{{ memory.title }}</text>
                  <text class="time">
                    {{ formatRelativeTime(memory.updateTime || memory.createTime) }}
                  </text>
                </view>
                <text class="preview">{{ memory.content.replace(/<[^>]+>/g, '') }}</text>
                <view class="meta-info">
                  <view class="media-count" v-if="memory.mediaList.length">
                    <image
                      src="https://at.alicdn.com/t/c/font_4444622_sl7c1kfu4h.png"
                      mode="aspectFit"
                      class="tag-icon attachment-icon"
                    />
                    <text>{{ memory.mediaList.length }}个文件</text>
                  </view>
                </view>
              </view>

              <view class="memory-media" v-if="memory.images?.length">
                <image :src="memory.images[0]" mode="aspectFill" class="cover-image" />
                <view class="image-count" v-if="memory.images.length > 1">
                  +{{ memory.images.length - 1 }}
                </view>
              </view>
            </view>
          </view>
        </template>

        <view v-else class="empty-state">
          <image
            src="https://at.alicdn.com/t/c/font_4444622_sl7c1kfu4h.png"
            mode="aspectFit"
            class="empty-image"
          />
          <text class="empty-title">开始记录精彩时刻</text>
          <text class="empty-desc">点击右上角的"+"创建你的第一条回忆</text>
        </view>
      </view>
    </scroll-view>

    <!-- 悬浮创建按钮 -->
    <view class="fab-button" @click="createMemory">
      <image src="https://cdn.xxx.com/icons/plus-white.png" mode="aspectFit" class="fab-icon" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useMemoriesStore } from '@/store/memories'

// 定义接口
interface Memorial {
  id: number
  title: string
  content: string
  createTime: string
  updateTime: string
  images: string[]
  hasAudio: boolean
  hasVideo: boolean
  mediaList: any[]
}

interface Folder {
  folderId: string
  folderName: string
  createTime: string
  updateTime: string
  memorial: Memorial[]
}

const memoriesStore = useMemoriesStore()
const isLoading = ref(true)
const searchText = ref('')

// 获取文件夹ID
const folderId = getCurrentPages().pop()?.options?.id

// 获取文件夹信息
const folder = computed(() => {
  const currentFolder = memoriesStore.currentUserData?.folders.find(
    (f: Folder) => f.folderId === folderId,
  )
  console.log('计算的文件夹:', currentFolder)
  return currentFolder
})

// 排序后的回忆列表
const sortedMemories = computed(() => {
  if (!folder.value?.memorial) {
    console.log('没有找到回忆数据')
    return []
  }

  const memories = [...folder.value.memorial]
  console.log('原始回忆数据:', memories)

  return memories
    .filter((memory) => {
      if (!searchText.value) return true
      const searchLower = searchText.value.toLowerCase()
      const contentText = memory.content.replace(/<[^>]+>/g, '') // 移除HTML标签
      return (
        memory.title?.toLowerCase().includes(searchLower) ||
        contentText.toLowerCase().includes(searchLower)
      )
    })
    .sort((a, b) => {
      const timeA = new Date(a.updateTime || a.createTime).getTime()
      const timeB = new Date(b.updateTime || b.createTime).getTime()
      return timeB - timeA
    })
})

// 获取最后更新时间
const getLastUpdateTime = () => {
  if (!sortedMemories.value.length) return '暂无更新'
  const lastMemory = sortedMemories.value[0]
  return formatRelativeTime(lastMemory.updateTime || lastMemory.createTime)
}

// 格式化相对时间
const formatRelativeTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  const minute = 60 * 1000
  const hour = minute * 60
  const day = hour * 24

  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < day * 30) {
    return `${Math.floor(diff / day)}天前`
  } else {
    return formatTime(time)
  }
}

// 创建新回忆
const createMemory = () => {
  const memory = memoriesStore.createMemory('新的回忆', folderId)
  if (memory) {
    uni.navigateTo({
      url: `/pages/memory/editor?id=${memory.id}&folderId=${folderId}`,
    })
  }
}

// 打开回忆
const openMemory = (id: number) => {
  uni.navigateTo({
    url: `/pages/memory/editor?id=${id}&folderId=${folderId}`,
  })
}

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
    date.getDate(),
  ).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(
    date.getMinutes(),
  ).padStart(2, '0')}`
}

// 刷新相关
const isRefreshing = ref(false)
const onRefresh = () => {
  isRefreshing.value = true
  setTimeout(() => {
    isRefreshing.value = false
  }, 1000)
}

// 添加返回方法
const onBack = () => {
  uni.navigateBack()
}

// 初始化数据
onMounted(async () => {
  try {
    console.log('开始初始化 store')
    await memoriesStore.init()
    console.log('当前文件夹ID:', folderId)
    console.log('store数据:', memoriesStore.currentUserData)
    console.log('文件夹数据:', folder.value)
    console.log('排序后的回忆:', sortedMemories.value)
  } finally {
    isLoading.value = false
  }
})
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f7f8fa;
}

.navbar {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  z-index: 100;
  margin-top: 45rpx;
  background: #fff;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
  .navbar-content {
    display: flex;
    align-items: center;
    height: 88rpx;
    padding: 0 24rpx;
    padding-top: var(--status-bar-height);
    margin-top: 60rpx;
    margin-bottom: 10rpx;
    .nav-left {
      padding: 16rpx;
      margin-left: -16rpx;

      .back-icon {
        width: 40rpx;
        height: 40rpx;
      }
    }

    .nav-center {
      display: flex;
      flex: 1;
      flex-direction: column;
      align-items: center;
      margin: 0 16rpx;

      .nav-title {
        font-size: 36rpx;
        font-weight: 600;
        line-height: 1.4;
        color: #1d2129;
      }

      .nav-subtitle {
        font-size: 24rpx;
        line-height: 1.2;
        color: #86909c;
      }
    }

    .nav-right {
      display: flex;
      gap: 8rpx;
      align-items: center;

      .action-btn {
        display: flex;
        align-items: center;
        // padding: 12rpx 16rpx;
        border-radius: 6rpx;
        transition: all 0.2s;

        &:active {
          background-color: rgba(0, 0, 0, 0.05);
        }

        .action-icon {
          width: 40rpx;
          height: 40rpx;
        }

        &.primary {
          gap: 4rpx;
          padding: 12rpx 24rpx;
          background: #1e63eb;
          border-radius: 6rpx;

          &:active {
            background: #1957d2;
          }

          .action-icon {
            width: 32rpx;
            height: 32rpx;
          }

          text {
            font-size: 28rpx;
            color: #fff;
          }
        }
      }
    }
  }

  .search-wrapper {
    padding: 0 24rpx 16rpx;

    .search-bar {
      display: flex;
      align-items: center;
      height: 72rpx;
      padding: 0 24rpx;
      background: #f2f3f5;
      border-radius: 6rpx;
      transition: all 0.2s;

      &:active {
        background: #e5e6eb;
      }

      .search-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 12rpx;
        opacity: 0.4;
      }

      input {
        flex: 1;
        font-size: 28rpx;
        color: #1d2129;

        &::placeholder {
          color: #86909c;
        }
      }
    }
  }
}

.list-header {
  padding: 32rpx 24rpx;
  margin-bottom: 24rpx;
  background: #fff;
  border-radius: 0 0 24rpx 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .header-main {
    display: flex;
    align-items: baseline;
    margin-bottom: 8rpx;

    .total-count {
      font-size: 48rpx;
      font-weight: 600;
      line-height: 1;
      color: #1e63eb;
    }

    .total-label {
      margin-left: 8rpx;
      font-size: 28rpx;
      color: #86909c;
    }
  }

  .update-time {
    font-size: 24rpx;
    color: #86909c;
  }
}

.memories-scroll {
  height: calc(100vh - 176rpx - var(--status-bar-height));
  margin-top: calc(220rpx + var(--status-bar-height));
}

.memories-list {
  padding: 0 24rpx;
}

.memory-card {
  margin-bottom: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;

  &:active {
    transform: scale(0.99);
  }

  .memory-content {
    padding: 24rpx;
  }

  .memory-main {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
  }

  .memory-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16rpx;

    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #1d2129;
    }

    .time {
      padding: 4rpx 12rpx;
      font-size: 24rpx;
      color: #86909c;
      background: #f2f3f5;
      border-radius: 24rpx;
    }
  }

  .preview {
    display: -webkit-box;
    overflow: hidden;
    font-size: 28rpx;
    line-height: 1.6;
    color: #4e5969;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }

  .meta-info {
    display: flex;
    gap: 16rpx;
    align-items: center;
    margin-top: 16rpx;

    .media-count {
      display: flex;
      gap: 4rpx;
      align-items: center;
      padding: 6rpx 12rpx;
      font-size: 24rpx;
      color: #86909c;
      background: #f2f3f5;
      border-radius: 6rpx;

      .tag-icon {
        width: 24rpx;
        height: 24rpx;
        opacity: 0.6;
      }
    }
  }

  .memory-media {
    position: relative;
    margin-top: 16rpx;

    .cover-image {
      width: 100%;
      height: 200rpx;
      object-fit: cover;
      border-radius: 12rpx;
    }

    .image-count {
      position: absolute;
      top: 12rpx;
      right: 12rpx;
      padding: 4rpx 12rpx;
      font-size: 24rpx;
      color: #fff;
      background: rgba(0, 0, 0, 0.6);
      backdrop-filter: blur(4px);
      border-radius: 24rpx;
    }
  }
}

.loading-skeleton {
  padding: 24rpx;
  margin-bottom: 24rpx;
  background: #fff;
  border-radius: 12rpx;

  .skeleton-content {
    width: 100%;
    height: 120rpx;
    background: #f2f3f5;
    border-radius: 4rpx;
  }
}

.fab-button {
  position: fixed;
  right: 32rpx;
  bottom: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  box-shadow: 0 8rpx 16rpx rgba(30, 99, 235, 0.2);

  .fab-icon {
    width: 48rpx;
    height: 48rpx;
  }

  &:active {
    transform: scale(0.95);
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 48rpx;
  text-align: center;

  .empty-image {
    width: 320rpx;
    height: 320rpx;
    margin-bottom: 48rpx;
    opacity: 0.8;
  }

  .empty-title {
    margin-bottom: 12rpx;
    font-size: 34rpx;
    font-weight: 500;
    color: #1d2129;
  }

  .empty-desc {
    font-size: 28rpx;
    color: #86909c;
  }
}
</style>
